package com.ruoyi.web.controller.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysAuthorization;
import com.ruoyi.system.service.ISysAuthorizationService;

/**
 * 系统授权Controller
 * 
 * @author ruoyi
 * @date 2025-10-15
 */
@RestController
@RequestMapping("/system/authorization")
public class SysAuthorizationController extends BaseController
{
    @Autowired
    private ISysAuthorizationService sysAuthorizationService;

    /**
     * 查询系统授权列表
     */
    @PreAuthorize("@ss.hasPermi('system:authorization:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysAuthorization sysAuthorization)
    {
        startPage();
        List<SysAuthorization> list = sysAuthorizationService.selectSysAuthorizationList(sysAuthorization);
        return getDataTable(list);
    }

    /**
     * 导出系统授权列表
     */
    @PreAuthorize("@ss.hasPermi('system:authorization:export')")
    @Log(title = "系统授权", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysAuthorization sysAuthorization)
    {
        List<SysAuthorization> list = sysAuthorizationService.selectSysAuthorizationList(sysAuthorization);
        ExcelUtil<SysAuthorization> util = new ExcelUtil<SysAuthorization>(SysAuthorization.class);
        util.exportExcel(response, list, "系统授权数据");
    }

    /**
     * 获取系统授权详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:authorization:query')")
    @GetMapping(value = "/{authId}")
    public AjaxResult getInfo(@PathVariable("authId") Long authId)
    {
        return success(sysAuthorizationService.selectSysAuthorizationByAuthId(authId));
    }

    /**
     * 验证授权码（匿名访问，用于登录验证）
     */
    @Anonymous
    @PostMapping("/validate")
    public AjaxResult validate(@RequestBody Map<String, String> params)
    {
        String authCode = params.get("authCode");
        boolean isValid = sysAuthorizationService.validateAuthorizationCode(authCode);
        
        if (isValid)
        {
            SysAuthorization authorization = sysAuthorizationService.selectSysAuthorizationByAuthCode(authCode);
            Map<String, Object> data = new HashMap<>();
            data.put("authName", authorization.getAuthName());
            data.put("expireTime", authorization.getExpireTime());
            data.put("isPermanent", authorization.getIsPermanent());
            data.put("maxUsers", authorization.getMaxUsers());
            return AjaxResult.success("授权验证通过", data);
        }
        else
        {
            return AjaxResult.error("授权码无效或已过期");
        }
    }

    /**
     * 检查系统授权状态（匿名访问，用于登录前检查）
     */
    @Anonymous
    @GetMapping("/checkStatus")
    public AjaxResult checkStatus()
    {
        boolean isAuthorized = sysAuthorizationService.isSystemAuthorized();
        Map<String, Object> data = new HashMap<>();
        data.put("isAuthorized", isAuthorized);
        
        if (isAuthorized)
        {
            SysAuthorization authorization = sysAuthorizationService.getCurrentValidAuthorization();
            if (authorization != null)
            {
                data.put("authName", authorization.getAuthName());
                data.put("expireTime", authorization.getExpireTime());
                data.put("isPermanent", authorization.getIsPermanent());
            }
        }
        
        return AjaxResult.success(data);
    }

    /**
     * 新增系统授权
     */
    @PreAuthorize("@ss.hasPermi('system:authorization:add')")
    @Log(title = "系统授权", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysAuthorization sysAuthorization)
    {
        return toAjax(sysAuthorizationService.insertSysAuthorization(sysAuthorization));
    }

    /**
     * 修改系统授权
     */
    @PreAuthorize("@ss.hasPermi('system:authorization:edit')")
    @Log(title = "系统授权", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysAuthorization sysAuthorization)
    {
        return toAjax(sysAuthorizationService.updateSysAuthorization(sysAuthorization));
    }

    /**
     * 删除系统授权
     */
    @PreAuthorize("@ss.hasPermi('system:authorization:remove')")
    @Log(title = "系统授权", businessType = BusinessType.DELETE)
	@DeleteMapping("/{authIds}")
    public AjaxResult remove(@PathVariable Long[] authIds)
    {
        return toAjax(sysAuthorizationService.deleteSysAuthorizationByAuthIds(authIds));
    }
}
